package com.atguigu.flink.chapter07;

import com.atguigu.flink.bean.WaterSensor;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

import java.time.Duration;

/**
 * @Author lizhenchao@atguigu.cn
 * @Date 2021/12/15 9:26
 */
public class Flink16_Timer_Project {
    public static void main(String[] args) throws Exception {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 20000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(1);
        SingleOutputStreamOperator<String> mainStream = env
            .socketTextStream("hadoop162", 9999)
            .map(line -> {
                String[] data = line.split(",");
                return new WaterSensor(data[0], Long.valueOf(data[1]), Integer.valueOf(data[2]));
            })
            .assignTimestampsAndWatermarks(
                WatermarkStrategy
                    .<WaterSensor>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                    .withTimestampAssigner((element, recordTimestamp) -> element.getTs())
            )
            .keyBy(WaterSensor::getId)
            .process(new KeyedProcessFunction<String, WaterSensor, String>() {
                
                private long timerTs;
                boolean isFirst = true;
                int lastVc = 0;
                
                @Override
                public void onTimer(long timestamp,
                                    OnTimerContext ctx,
                                    Collector<String> out) throws Exception {
                    String id = ctx.getCurrentKey();
                    out.collect(id + " 水位连续5s上升, 预警....");
                    isFirst = true;
                }
                
                @Override
                public void processElement(WaterSensor value,
                                           Context ctx,
                                           Collector<String> out) throws Exception {
                    if (isFirst) {  // 第一条数据进来, 注册定时器
                        // ctrl+shift+f
                        timerTs = value.getTs() + 5000;
                        
                        System.out.println("第一条数据进来...." + timerTs);
                        isFirst = false;
                        ctx.timerService().registerEventTimeTimer(timerTs);
                    } else {
                        // 判断相比上调数据是否上升
                        Integer currentVc = value.getVc();
                        if (currentVc < lastVc) {
                            System.out.println("下降, 取消定时器, 并注册新的当定时器");
                            ctx.timerService().deleteEventTimeTimer(timerTs);
                            timerTs = value.getTs() + 5000;
                            ctx.timerService().registerEventTimeTimer(timerTs);
                        } else {
                            System.out.println("上升, 不需要任何的操作...");
                        }
                    }
                    
                    // 这次的水位赋值给lastVc, 等下次进来的就是上次了
                    lastVc = value.getVc();
                }
            });
    
        mainStream.print();
        env.execute();
    }
}
